// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  let author = event.author || '' // 关键字作者
  let poem = event.poem || '' // 诗名
  let category = event.category || '' // 0:古诗词；1：小学；2：初中；3：高中 

  let pages = event.pages || 0 // 页码
  let pagesTotal = event.pagesTotal || 10 // 获取页数
  if(poem!=''&& category==''){
    return await db.collection('miscellanies')
    .where(_.or([ // 多个名称搜索
      {
        poem:{
          $regex:'.*' + poem,
          $options:'i'
        }
      },
      {
        author:{
          $regex:'.*' + poem,
          $options:'i'
        }
      }
    ]))
    .limit(pagesTotal)
    .skip(pages)
    .orderBy('hits','desc')
    .get()
  } else if(category!=0){ // 点击古诗词
    return await db.collection('miscellanies')
    .where({
      category:_.in([category])
    })
    .limit(pagesTotal)
    .skip(pages)
    .orderBy('hits','desc')
    .get()
  }else if(author!=''){ // 搜索诗人
    return await db.collection('miscellanies')
    .where({
      author
    })
    .limit(pagesTotal)
    .skip(pages)
    .orderBy('hits','desc')
    .get()
  }else { // 搜索全部
    return await db.collection('miscellanies')
      .limit(pagesTotal)
      .skip(pages)
      .orderBy('hits','desc')
      .get()
  }


}